<template>
  <div id="app">
    <h1>购物车</h1>
    <div v-for="item in items" :key="item.id">
      <span>{{ item.name }} - ${{ item.price }} - 数量：{{ getQuantity(item) }}</span>
      <button @click="addToCart(item)">+</button>
      <button @click="removeFromCart(item)">-</button>
    </div>
    <h2>总价: ${{ totalPrice }}</h2>
  </div>
</template>

<script>
export default {
  computed: {
    items() {
      return [
        { id: 1, name: '手机', price: 1000 },
        { id: 2, name: '电脑', price: 2000 },
        { id: 3, name: '键盘', price: 200 }
      ];
    },
    totalPrice() {
      return this.$store.getters.totalPrice;
    }
  },
  methods: {
    addToCart(item) {
      this.$store.commit('addToCart', item);
    },
    removeFromCart(item) {
      this.$store.commit('removeFromCart', item);
    },
    getQuantity(item) {
      const cartItem = this.$store.state.cart.find(i => i.id === item.id);
      return cartItem ? cartItem.quantity : 0;
    }
  }
}
</script>